package com.amphiprion.prototype.util;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

class ResolutionOptimizer {
	private List<Float> ratioCoordLimits = new ArrayList<Float>();
	private List<String> dirs = new ArrayList<String>();
	private List<Float> normailzedScales = new ArrayList<Float>();
	// private int coordWith;
	// private int coordHeight;
	// private int deviceWidth;
	// private int deviceHeight;
	protected float screenScale;

	ResolutionOptimizer(int coordWidth, int coordHeight, float deviceWidth, float deviceHeight) {
		// this.coordWith = coordWidth;
		// this.coordHeight = coordHeight;
		// this.deviceWidth = deviceWidth;
		// this.deviceHeight = deviceHeight;

		if (deviceWidth > deviceHeight) {
			if (coordWidth > coordHeight) {
				screenScale = Math.min(deviceWidth / coordWidth, deviceHeight / coordHeight);
			} else {
				screenScale = Math.min(deviceWidth / coordHeight, deviceHeight / coordWidth);
			}
		} else {
			if (coordWidth > coordHeight) {
				screenScale = Math.min(deviceWidth / coordHeight, deviceHeight / coordWidth);
			} else {
				screenScale = Math.min(deviceWidth / coordWidth, deviceHeight / coordHeight);
			}
		}

	}

	public void addOptimization(float ratioCoordLimit, String dir, float normalizeScale) {
		boolean added = false;
		for (int i = 0; i < ratioCoordLimits.size(); i++) {
			if (ratioCoordLimits.get(i) > ratioCoordLimit) {
				ratioCoordLimits.add(i, ratioCoordLimit);
				dirs.add(i, dir);
				normailzedScales.add(i, normalizeScale);
				added = true;
				break;
			}
		}
		if (!added) {
			ratioCoordLimits.add(ratioCoordLimit);
			dirs.add(dir);
			normailzedScales.add(normalizeScale);
		}
	}

	public NormalizedBitmap getNormalizedBitmap(String uri) {
		String prefix = null;
		float normalizedScale = 1.0f;
		for (int i = 0; i < ratioCoordLimits.size(); i++) {
			if (ratioCoordLimits.get(i) >= screenScale) {
				prefix = dirs.get(i);
				normalizedScale = normailzedScales.get(i);
			}
		}

		InputStream is = null;
		if (prefix != null) {
			is = BitmapUtil.class.getResourceAsStream("/images/" + prefix + "/" + uri);
		}
		if (is == null) {
			is = BitmapUtil.class.getResourceAsStream("/images/default/" + uri);
			normalizedScale = 1.0f;
		}
		Bitmap b = BitmapFactory.decodeStream(is);

		NormalizedBitmap nb = new NormalizedBitmap();
		nb.bitmap = b;
		nb.normalizedScale = normalizedScale;

		return nb;
	}
}
